<template>
  <ElContainer style="height: 100%">
    <ElMain class="archive-info">
      <ElForm :inline="true">
        <ElTabs
          v-if="tabShow"
          ref="tabsRef"
          type="card"
          v-model="tabInfo.activeName"
          class="demo-tabs"
          @tab-click="tabInfo.handleTabClick"
        >
          <ElTabPane label="一般情况" name="first">
            <BaseInfo
              :base-info="formCard.baseInfo"
              ref="baseInfo"
              :personal-archive="personalArchive"
              :user-name="userName"
            />
          </ElTabPane>
          <ElTabPane label="生活方式" name="second">
            <Lifestyle :is-visible="tabInfo.activeName==='second'" :lifestyle="formCard.lifestyle" ref="lifestyle" />
          </ElTabPane>
          <ElTabPane label="查体信息" name="third">
            <CheckBody :check-body="formCard.checkBody" ref="bodyCheck" />
          </ElTabPane>
          <ElTabPane label="辅助检查" name="fourth" v-if="!isHealthCheck">
            <AuxiliaryCheck
              :auxiliary-check="formCard.auxiliaryCheck"
              ref="auxiliaryCheck"
            />
          </ElTabPane>
          <ElTabPane label="脏器检查" name="five">
            <OrganFunction
              :organ-function="formCard.organFunction"
              ref="organFunction"
            />
          </ElTabPane>
          <ElTabPane label="健康问题" name="six">
            <ExistIssue
              :exist-issue="formCard.existIssue"
              ref="existIssue"
            />
          </ElTabPane>
          <ElTabPane label="治疗情况" name="seven">
            <TreatmentCondition
              :treatment-condition="formCard.treatmentCondition"
              ref="treatmentCondition"
            />
          </ElTabPane>
          <ElTabPane label="健康评价" name="eight">
            <HealthEvaluation
              :health-evaluation="formCard.healthEvaluation"
              :is-visible="tabInfo.activeName==='eight'"
              :get-life-style-data="getLifeStyleData"
              :get-exist-issue-data="getExistIssueData"
              ref="healthEvaluation"
            />
          </ElTabPane>
        </ElTabs>
      </ElForm>
    </ElMain>
  </ElContainer>
  <MyDialog
    :handle-confirm-click="agedTcmDialog.handleConfirmClick"
    v-model:visible="agedTcmDialog.visible"
  >
    <AgedTcm ref="agedTcmRef" />
  </MyDialog>
</template>
<script lang="ts" setup>
import { nextTick, reactive, ref, toRaw } from "vue";
import { IA00_03, IA00_04, modelUtils } from "@/model";
import Lifestyle from "./Lifestyle.vue";
import OrganFunction from "./OrganFunction.vue";
import CheckBody from "./CheckBody.vue";
import AuxiliaryCheck from "./AuxiliaryCheck.vue";
import ExistIssue from "./ExistIssue.vue";
import HealthEvaluation from "./HealthEvaluation.vue";
import BaseInfo from "./BaseInfo.vue";
import TreatmentCondition from "./TreatmentCondition.vue";
import { saveHealthArchives } from "@/api/archives";
import { ElContainer, ElMain, ElForm, ElTabs, ElTabPane } from "element-plus";
import AgedTcm from "@/views/AgedTcm/index.vue";
import { MyDialog } from "@/components";
import { cloneDeep } from "lodash-es";

const isHealthCheck = ref<boolean>(import.meta.env.MODE === "health_check");
const tabsRef = ref<InstanceType<typeof ElTabs>>();
const tabInfo = ref({
  activeName: "first",
  handleTabClick(val) {
    setTimeout(() => {
      console.log(tabsRef.value?.$el.querySelector(".el-tabs__content"));
      const content: HTMLDivElement =
        tabsRef.value?.$el.querySelector(".el-tabs__content");
      content.scrollTo({
        top: 0,
        left: 0,
      });
    }, 200);
    console.log(toRaw(val))
  },
});
//新增的时候要传入个人档案信息
//编辑的时候不需要个人档案信息
const props = defineProps<{
  personalArchive?: Partial<IA00_03>;
  healthArchive?: Partial<IA00_04>;
  // 兼容终端
  userName?: string;
}>();
const handleTabChange = () => {
  setTimeout(() => {}, 200);
};
const paddingValue = (row, target) => {
  Object.keys(target).forEach((item) => {
    target[item] = row[item] || target[item];
  });
  return target;
};
const tabShow = ref(true);
const resetArchive = () => {
  const rawArchive = toRaw(cloneDeep(props.healthArchive));
  const data = {
    linkInfo: {
      //关联信息：个人档案健康档案号
      id: rawArchive?.id || null,
    },
    lifestyle: rawArchive
      ? paddingValue(rawArchive, modelUtils.createLifestyle())
      : modelUtils.createLifestyle(),
    organFunction: rawArchive
      ? paddingValue(rawArchive, modelUtils.createOrganFunction())
      : modelUtils.createOrganFunction(),
    checkBody: rawArchive
      ? paddingValue(rawArchive, modelUtils.createCheckBody())
      : modelUtils.createCheckBody(),
    auxiliaryCheck: rawArchive
      ? paddingValue(rawArchive, modelUtils.createAuxiliaryCheck())
      : modelUtils.createAuxiliaryCheck(),
    existIssue: rawArchive
      ? paddingValue(rawArchive, modelUtils.createExistIssue())
      : modelUtils.createExistIssue(),
    treatmentCondition: rawArchive
      ? paddingValue(rawArchive, modelUtils.createTreatmentCondition())
      : modelUtils.createTreatmentCondition(),
    healthEvaluation: rawArchive
      ? paddingValue(rawArchive, modelUtils.createHealthEvaluation())
      : modelUtils.createHealthEvaluation(),
    baseInfo: rawArchive
      ? paddingValue(rawArchive, modelUtils.createBaseInfo())
      : modelUtils.createBaseInfo(),
  };
  if (props.personalArchive?.id) {
    const person = cloneDeep(toRaw(props.personalArchive));
    data.baseInfo.a00_03_03 = person.a00_03_03;
    data.baseInfo.a00_03_05 = person.a00_03_05;
  }

  console.log("formCard", data);
  return data;
};
const formCard = ref(resetArchive());

// 人员档案信息

const organFunction = ref<InstanceType<typeof OrganFunction>>();
const lifestyle = ref<InstanceType<typeof Lifestyle>>();
const bodyCheck = ref<InstanceType<typeof CheckBody>>();
const auxiliaryCheck = ref<InstanceType<typeof AuxiliaryCheck>>();
const existIssue = ref<InstanceType<typeof ExistIssue>>();
const treatmentCondition = ref<InstanceType<typeof TreatmentCondition>>();
const healthEvaluation = ref<InstanceType<typeof HealthEvaluation>>();
const baseInfo = ref<InstanceType<typeof BaseInfo>>();
const validateForm = async () => {
  try {
    // const values = await Promise.all([
    //   organFunction.value?.validateForm(),
    //   lifestyle.value?.validateForm(),
    //   bodyCheck.value?.validateForm(),
    //   auxiliaryCheck.value?.validateForm(),
    //   existIssue.value?.validateForm(),
    //   treatmentCondition.value?.validateForm(),
    //   healthEvaluation.value?.validateForm(),
    //   baseInfo.value?.validateForm(),
    // ]);
    // if (values.every((item) => item!==false)) {
    //   console.log("检验通过");
    //   return true;
    // }
    // return false;
    return true;
  } catch (e) {
    return false;
  }
};

const validate = async () => {
  return await validateForm();
};

const save = async () => {
  const data = await getData();
  const result = await saveHealthArchives(toRaw(data));
  return result;
};
const getLifeStyleData = ()=>{
  return lifestyle.value?.getData()
}
const getExistIssueData = ()=>{
  return existIssue.value.getData()
}
const getData = async () => {
  return new Promise((resolve, reject) => {
    validate()
      .then((data) => {
        if (data) {
          const sendData = {};
          const organFunctionData = toRaw(organFunction.value?.getData());
          const lifestyleData = toRaw(lifestyle.value?.getData());
          const bodyCheckData = toRaw(bodyCheck.value?.getData());
          const auxiliaryCheckData = toRaw(auxiliaryCheck.value?.getData());
          const existIssueData = toRaw(existIssue.value?.getData());
          const treatmentConditionData = toRaw(
            treatmentCondition.value?.getData()
          );
          const healthEvaluationData = toRaw(healthEvaluation.value?.getData());
          const baseInfoData = toRaw(baseInfo.value?.getData());
          Object.assign(
            sendData,
            organFunctionData,
            lifestyleData,
            bodyCheckData,
            auxiliaryCheckData,
            existIssueData,
            treatmentConditionData,
            healthEvaluationData,
            baseInfoData,
            toRaw(formCard.value.linkInfo)
          );
          resolve(toRaw(sendData));
        }
        reject({
          data: false,
          message: "校验失败",
        });
      })
      .catch((e) => {
        reject("校验失败");
        console.error(e);
      });
  });
};

//老年人体质调查表
const agedTcmRef = ref();
const agedTcmDialog = reactive({
  visible: false,
  handleConfirmClick: async () => {
    return await agedTcmRef.value.save();
  },
});
// onMounted(() => {
//   console.log()
//   if (dayjs().diff(personalArchive.value.a00_03_09, "year") > 20) {
//     ElMessageBox.confirm("老年人体检或随访前是否先录入老年人中医药管理?", "提示", {
//       callback(val) {
//         if (val === "confirm") {
//           agedTcmDialog.visible = true
//         }
//       }
//     })
//   }
// })

const setArchive = () => {
  tabShow.value = false;
  formCard.value = resetArchive();
  nextTick(() => {
    tabShow.value = true;
  });
};
defineExpose({ save, getData, setArchive });
</script>
<style lang="scss">
.input-number-width {
  .el-input__inner {
    width: 60px;
  }
}

.archive-info {
  input[type="number"] {
    width: 100px;
  }
  .el-form {
    height: 100%;
    .el-tabs {
      height: 100%;
      .el-tabs__content {
        overflow: auto;
        height: calc(100% - 80px);
      }
    }
  }
}

.el-table__row .el-form-item {
  margin-bottom: 0;
}
</style>
